package engine.logic.login
{
	import engine.data.GamePlayer;
	import engine.data.ModelLocator;
	import engine.event.BaseNetEvent;
	import engine.logic.ActSee;
	import engine.logic.AlertLogic;
	import engine.logic.event.LogicEvent;
	import engine.logic.loading.LoadingLogic;
	import engine.net.NetSocket;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.NetMgr;
	import engine.net.mgr.SystemReturn;
	import engine.net.mgr.SystemSender;
	import engine.scene.SceneManager;
	import engine.ui.AlertTimeLoseUI;
	import engine.ui.AlertUI;
	
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.SharedObject;
	import flash.utils.getTimer;
	
	import newx.com.config.StaticIni;
	import newx.utils.debug.IO;

	public class NormalLogin implements ILoginLogic
	{
		public	var UICompleteFunc:Function = null;
		public function NormalLogin()
		{
			if(null		!=	_self)	
				throw new Error("LoginLogic，单例错误");
			
			LoginLogic.LoginMode	=	LoginLogic.Mode_NormalLogin;
			
			init();
		}
		
		private var _create	:Boolean = false;
		
		static private var _self:NormalLogin
		
		public function get create():Boolean
		{
			return _create;
		}

		public function set create(value:Boolean):void
		{
			_create = value;
		}

		static public function getInstance():NormalLogin
		{
			if(null		==	_self)	_self=new NormalLogin();
			return _self
		}
		
		private var _loginInfo:Object;
		private var _roleCreateInfo:Object;
		
		/**时间*/		
		private 			var _time		:int;
		
		private			var _socketTime : int;
		
		private var _loginUI:LoginUI;
		
		private var _resReadyCallBack:Function;
		
		private function init():void
		{
			this.invoke();
			//先取浏览器地址，是联合运营登陆，并且已经有角色了，则直接
			loginUI.show({type:LoginUI.ShowLogin});
		}
		
		private function invoke():void
		{
			ModelLocator.getInstance().addEventListener(BaseNetEvent.LOGIN_SUCCESS,loginSuccessHandler);
			ModelLocator.getInstance().addEventListener(BaseNetEvent.SERVER_ERROR,loginFailHandler);
			
//			ModelLocator.getInstance().addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_ROLE_CREATED),roleCreateReadyHandler);
			loginUI.completeCallBack=loginUIFeedBackHandler;
			
			ModelLocator.getInstance().addEventListener(BaseNetEvent.SERVER_QUEUE,serverQueueHandler);
			
			NetSocket.getInstance().addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandle);
			
			ModelLocator.getInstance().addEventListener(LogicEvent.INIT_COMPLETE,onGameInitComplete);
//			ModelLocator.getInstance().addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_PLAYER_NO_CASTLE),roleCreateReadyHandler);
		}
		
		private function onGameInitComplete(e:LogicEvent):void
		{
			if(UICompleteFunc!=null)UICompleteFunc.call();
		}
		private function recycle():void
		{
			ModelLocator.getInstance().removeEventListener(BaseNetEvent.LOGIN_SUCCESS,loginSuccessHandler);
			ModelLocator.getInstance().removeEventListener(BaseNetEvent.SERVER_ERROR,loginFailHandler);
			
//			ModelLocator.getInstance().removeEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_ROLE_CREATED),roleCreateReadyHandler);
			ModelLocator.getInstance().removeEventListener(BaseNetEvent.SERVER_QUEUE,serverQueueHandler);
			
			if(	null	!=	_loginUI)
			{
				_loginUI.completeCallBack=null;
				_loginUI.recycle();
				_loginUI	=	null;
			}
			LoginAlert.recycle();
		}
		
		private function socketConnectSucceedHandler():void
		{
			IO.traceLog("服务器连接成功");
			ActSee.PostLoginStatus(22002,1,getTimer() - _socketTime);
			ActSee.PostClientStatus(8999,1,getTimer() - _socketTime);
			if(_time == 0)_time = getTimer();
			ModelLocator.getInstance().dispatchEvent(new LogicEvent(LogicEvent.CONNECT_SUCCESS));
			
			LoadingLogic.getInstance().forceVisible=true;
			
			if(!LoginCallLater.AllSwfReady)
			{
				LoginUI._loginContainer.visible = false;
//				WaitingForScene.start();
				LoadingLogic.getInstance().nxLoading.y	= 0;
			}
		}
		
		private function socketConnectFailHandler(e:IOErrorEvent):void
		{
			LoginAlert.showAlert(this.getConnectErrorMsg());
		}

//		private function roleCreateReadyHandler(e:CustomMsgEvent):void
//		{
////			if(	1	==	e.pList[0])
////			{
//			if(	_roleCreateInfo	&&	_roleCreateInfo.hasOwnProperty("castleId"))
//			{
//				var castleStr:String	=  getCastleById(_roleCreateInfo.castleId);
//				
//				SystemSender.getInstance().CustomMsg(
//					CustomToServerFlag.CLIENT_CUSTOMMSG_APPLYIN_CASTLE,castleStr);
//			}
////			}
//		}
		
		/**服务器连接成功后发送登陆信息*/
		private function loginSuccessHandler(e:BaseNetEvent):void
		{
			NxLoaderProxy.setVisible(true);
			ModelLocator.getInstance().gameStatus	=	ModelLocator.Gameing;
			
			IO.traceLog("登录成功",ModelLocator.getInstance().player.nRoles,e.data[0]);
			
			var overTime : int = getTimer() - _time;
			
			var loginType:uint=e.data[0];
			
			switch(loginType)
			{
				//登录失败
				case GamePlayer.LoginType_Fail:
					IO.traceLog("登录失败");
					loginUI.hide();
//					trace("-------------1");
					break;
				//登录成功，无角色,创建角色
				case GamePlayer.LoginType_NoRole:
					_create	=	true;
					loginUI.hide();
					loginUI.show({type:LoginUI.ShowRoleCreate});
					SceneManager.isCreate = true;
					break;
				//登录成功，有角色，但没有选择角色
				case GamePlayer.LoginType_NotLoginRole:
//					loginUI.hide();
					if(_create)
					{
						//ActSee.PostLoginStatus(22003,1,overTime);
					}else
					{
						ActSee.PostLoginStatus(22005,1,overTime);
					}
					_time = getTimer();
					SystemReturn.time = _time;
					var name:String=ModelLocator(e.target).player.wsName;
					SystemSender.getInstance().SelectRole(name);
//					trace("-------------3");
					break;
				//登录成功，且选择了登录的角色
				case GamePlayer.LoginType_LoginRole:
//					trace("-------------开始等待");
//					WaitingForScene.start();
					loginUI.hide();
					this.recycle();//出口
//					trace("-------------4");
					break;
			}
			
			if( loginType != GamePlayer.LoginType_Fail )
			{//登陆成功并且勾选了保持账号
				var userdata:SharedObject	=	SharedObject.getLocal("userdata");
				if( UserInfoForm.IsSaveName )
				{
					userdata.data.userName	=	LoginGroup._userName;
				}
				if( UserInfoForm.IsSavePwd )
				{
					userdata.data.password	=	LoginGroup._password;
				}
			}
		}
		
		private function getRandomName():String
		{
			var firstNameLen 	: int = 772;
			var boyNameLen 		: int = 280;
			var girlNameLen 	: int = 223;
			
			return StaticIni.getSwfLangStr( "firstname_" + int( Math.random() * firstNameLen ) )
				+ StaticIni.getSwfLangStr( "secondname_girl_" + int( Math.random() * girlNameLen ) );
		}
		
//		//登录结束，进入游戏
//		private function loginOver():void
//		{
//			this.removeAll();
//			ModelLocator.getInstance().dispatchEvent(new LogicEvent(LogicEvent.LOGIN_COMPLETE));
//		}
		
		//登陆失败
		private function loginFailHandler(e:BaseNetEvent):void
		{
			NxLoaderProxy.setVisible(false);
			var		error:int	=	e.data[0];
			
			var errorStr:String=this.getLoginFailMsg(error);
			
			ActSee.PostLoginStatus(22002,error,getTimer() - _time);
			
			if(	error	==	51069)//防沉迷提示
			{
				if(LoginCallLater.AllSwfReady)
				{
					AlertTimeLoseUI.getInstance().showTimeLoseUI("0",AlertLogic.TIPSTYPE_SYSTEM_UNENTHRALL,errorStr);
				}
				else
				{
					UICompleteFunc	=	function():void
					{
						AlertTimeLoseUI.getInstance().showTimeLoseUI("0",AlertLogic.TIPSTYPE_SYSTEM_UNENTHRALL,errorStr);
					}
				}
			}
			else
			{
				LoginAlert.showAlert(String(error));
				WaitingForScene.end();
				LoginUI._loginContainer.visible = true;
			}
//			LoginAlert.hide();
			
			showProtectionLoginUI( error );
			//发送错误码
//			ActSee.PostLoginStatus(3,error,getTimer() - _time);
			
//			var errorStr:String=this.getLoginFailMsg(error);
			
//			if(_loginAlert)
//				_loginAlert.showAlert(errorStr);
			
//			LoadingLogic.getInstance().hide();
		}
		
		private function showProtectionLoginUI( error : int ):void
		{
//			51088 -- 您的帐号绑定的令牌密保已过期，请解除绑定或更换后再登录
//			51089 -- 您的帐号绑定的令牌密保需要效验，请到会员中心操作
//			51090 -- 您的令牌密保错误，禁止登录
//			51091 -- 此帐号受令牌密保服务保护，请选择令牌密保方式登录

			if( error == 51088 || error == 51089 || error == 51090 || error == 51091)
			{
				_loginUI.showProtectionLogin();
			}
		}
		
		private function securityErrorHandle(e:SecurityErrorEvent):void
		{
			LoginAlert.showAlert(this.getConnectErrorMsg());
		}
		
		private function serverQueueHandler(e:BaseNetEvent):void
		{
			IO.traceLog("开始排队",e.data);
			
			var queueMsg:String	=	StaticIni.getSwfLangStrVar("130",e.data);
			LoginAlert.showAlert(queueMsg);
		}
		
		//登录界面 登录信息回调
		private function loginUIFeedBackHandler(loginInfo:Object):void
		{
			var type:String=loginInfo.type;
			
			switch(type)
			{
				case LoginUI.FeedBackLoginResReady:
					if(	null	!=	_resReadyCallBack)
					{
						_resReadyCallBack();
					}
					break;
				
				case LoginUI.FeedBackLoign:	
					IO.traceLog("正常登录,ip:",loginInfo.ip,"port:",loginInfo.port,"userName:",loginInfo.userName,"password:",loginInfo.password);
					
					/**服务器IP*/
					ActSee.s_serverIp	=		loginInfo.ip;
					/**账号*/
					ActSee.s_account	=		loginInfo.userName;
					
					LoginAlert.showAlert(getLoginStartMsg(),false);//正在登陆，请稍后，不准关闭
					_loginInfo=loginInfo;
					
					_socketTime	= getTimer();
					
					
					LoginCallLater.callLater(
									LoginCallLater.UiResReady|LoginCallLater.ConfigDataReady,
									NetMgr.netConnect,
									[loginInfo.ip,loginInfo.port,socketConnectSucceedHandler]
									);
					
					LoginCallLater.callLater(
										LoginCallLater.UiResReady|LoginCallLater.ConfigDataReady,
										SystemSender.getInstance().Login,
										[loginInfo.userName,loginInfo.password]
									);//|LoginCallLater.AllReady
					
					ModelLocator.getInstance().HandleProperties("serverId",loginInfo.serverId);
					ModelLocator.getInstance().player.sAccount	=	loginInfo.userName;
//					NetMgr.netConnect(loginInfo.ip,loginInfo.port,socketConnectSucceedHandler);
//					SystemSender.getInstance().Login(loginInfo.userName,loginInfo.password);
					//保存临时用户名
//					new JsToFlashLogic().userName	=	loginInfo.userName;
					break;
				
				case LoginUI.FeedBackRoleCreate:
					_roleCreateInfo=loginInfo;
					//send message
					_time = getTimer();
					_create = true;
					SystemSender.getInstance().CreatRole(loginInfo.roleName,loginInfo.raceId,loginInfo.sexId,0,loginInfo.occuId,
						getCastleById(_roleCreateInfo.castleId));
					WaitingForScene.start();
//					var castleStr:String	=  getCastleById(_roleCreateInfo.castleId);
//					
//					SystemSender.getInstance().CustomMsg(
//						CustomToServerFlag.CLIENT_CUSTOMMSG_APPLYIN_CASTLE,castleStr);
					
					break;
			}
		}
		
		private function get loginUI():LoginUI
		{
			if(null		==	_loginUI)	
				_loginUI=new LoginUI();
			
			return _loginUI;
		}
		
		/**通过id获取，城堡标识*/
		private function getCastleById(castleId:int):String
		{
			var obj:Object=StaticIni.getIniObj("Castle_"+castleId);
			var name:String=obj["CastleNameID"];
			
			return name;
		}

		private function getServerSelectTip():String
		{
			return "UIStr_1000873" // StaticIni.getSwfLangStr("UIStr_1000873");
		}
		
		private function getLoginStartMsg():String
		{
			return 	"UIStr_1000867" // StaticIni.getSwfLangStr("loingNow");
		}
		private function getLoginFailMsg(errorId:int):String
		{
			return StaticIni.getSwfLangStr(String(errorId));
		}
		private function getConnectErrorMsg():String
		{
			return "UIStr_1000868";//StaticIni.getSwfLangStr("UIStr_1000868");
		}
		
		
		
		public function set readyCallBack(cb:Function):void
		{
			_resReadyCallBack=cb;
		}
		
	}
}